package com.yxjx.duoxue.customview;

import com.yxjx.duoxue.R;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class YxRefreshListView extends ListView implements OnScrollListener {

	private final static int PULL_REFRESH_NONE = 0; // 正常状态
	private final static int PULL_REFRESH_ENTER = 1; // 进入下拉刷新状态
	private final static int PULL_REFRESH_OVER = 2; // 进入松手刷新状态
	private final static int PULL_REFRESH_EXIT = 3; // 松手后反弹后加载状态
	
	private final static int REFRESH_BACKING = 0;      //反弹中
	private final static int REFRESH_BACED = 1;        //达到刷新界限，反弹结束后
	private final static int REFRESH_RETURN = 2;       //没有达到刷新界限，返回
	private final static int REFRESH_DONE = 3;         //加载数据结束

	private int mPullRefreshState = PULL_REFRESH_NONE; // 记录刷新状态

	private View mHeadView;
	private TextView mHeadText;
	private View mFootView;
	private TextView mFootText;

	private int mCurrentScrollState;
	private int mHeadHeight;

	// store in TouchEvent
	private float mDownY;
	private float mMoveY;
	
	//注入接口
	private Object mRefreshObject = null; //传值
	private RefreshListener mRefreshListener = null;
	
	public void setOnRefreshListener(RefreshListener refreshListener) {
	    this.mRefreshListener = refreshListener;
	}

	public YxRefreshListView(Context context) {
		// TODO Auto-generated constructor stub
		this(context, null);
	}

	public YxRefreshListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private void init(Context context) {
		mHeadView = LayoutInflater.from(getContext()).inflate(
				R.layout.segment_refresh_list_head, null);
		mHeadText = (TextView) mHeadView.findViewById(R.id.refresh_desc);
//		mFootView = LayoutInflater.from(getContext()).inflate(resource, root);
		//test

		addHeaderView(mHeadView, null, false);
		setSelection(1);
		setOnScrollListener(this);

		measureChildView(mHeadView);
		mHeadHeight = mHeadView.getMeasuredHeight();
	}

	private void measureChildView(View child) {
		ViewGroup.LayoutParams lp = child.getLayoutParams();
		if (lp == null) {
			lp = new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}

		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, lp.width);
		int lpHeight = lp.height;
		int childHeightSpec = 0;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
					MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0,
					MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL
				&& firstVisibleItem == 0
				&& (mHeadView.getBottom() < mHeadHeight && mHeadView
						.getBottom() >= 0)) {
			// 进入且仅进入下拉刷新状态
			if (mPullRefreshState == PULL_REFRESH_NONE) {
				mPullRefreshState = PULL_REFRESH_ENTER;
			}

		} else if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL
				&& firstVisibleItem == 0
				&& (mHeadView.getBottom() >= mHeadHeight)) {
			// 下拉达到界限，进入松手刷新状态
			if (mPullRefreshState == PULL_REFRESH_ENTER
					|| mPullRefreshState == PULL_REFRESH_NONE) {
				mPullRefreshState = PULL_REFRESH_OVER;
				// 下面是进入松手刷新状态需要做的一个显示改变
				mDownY = mMoveY;// 用于后面的下拉特殊效果
				mHeadText.setText("松手刷新");
			}

		} else if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL
				&& firstVisibleItem != 0) {
			// 不刷新了
			if (mPullRefreshState == PULL_REFRESH_ENTER) {
				mPullRefreshState = PULL_REFRESH_NONE;
			}

		} else if (mCurrentScrollState == SCROLL_STATE_FLING
				&& firstVisibleItem == 0) {
			// 飞滑状态，不能显示出header，也不能影响正常的飞滑
			// 只在正常情况下才纠正位置
			if (mPullRefreshState == PULL_REFRESH_NONE) {
				setSelection(1);
			}
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		mCurrentScrollState = scrollState;
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mDownY = ev.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			mMoveY = ev.getY();
			if (mPullRefreshState == PULL_REFRESH_OVER) {
				mHeadView.setPadding(
						mHeadView.getPaddingBottom(), 
						(int) ((mMoveY - mDownY) / 3), 
						mHeadView.getPaddingLeft(),
						mHeadView.getPaddingRight());
			}
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			//when you action up, it will do these:
            //1. roll back until header topPadding is 0
            //2. hide the header by setSelection(1)
            if (mPullRefreshState == PULL_REFRESH_OVER || mPullRefreshState == PULL_REFRESH_ENTER) {
                new Thread() {
                    public void run() {
                        Message msg;
                        while(mHeadView.getPaddingTop() > 1) {
                            msg = mHandler.obtainMessage();
                            msg.what = REFRESH_BACKING;
                            mHandler.sendMessage(msg);
                            try {
                                sleep(5);//慢一点反弹，别一下子就弹回去了
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        msg = mHandler.obtainMessage();
                        if (mPullRefreshState == PULL_REFRESH_OVER) {
                            msg.what = REFRESH_BACED;//加载数据完成，结束返回
                        } else {
                            msg.what = REFRESH_RETURN;//未达到刷新界限，直接返回
                        }
                        mHandler.sendMessage(msg);
                    };
                }.start();
            }
			break;
		default:
			break;
		}
		return super.onTouchEvent(ev);
	}
	
	private Handler mHandler = new Handler(){

		@Override
	    public void handleMessage(Message msg) {
	        switch (msg.what) {
	        case REFRESH_BACKING:
	            mHeadView.setPadding(mHeadView.getPaddingLeft(),
	                    (int) (mHeadView.getPaddingTop()*0.75f),
	                    mHeadView.getPaddingRight(),
	                    mHeadView.getPaddingBottom());
	            break;
	        case REFRESH_BACED:
	            mHeadText.setText("正在加载");
	            mPullRefreshState = PULL_REFRESH_EXIT;
	            new Thread() {
	                public void run() {
	                	try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	                    if (mRefreshListener != null) {
	                    	mRefreshListener.refreshing();
						}//处理后台加载数据
	                    Message msg = mHandler.obtainMessage();
	                    msg.what = REFRESH_DONE;
	                    //通知主线程加载数据完成
	                    mHandler.sendMessage(msg);
	                };
	            }.start();
	            break;
	        case REFRESH_RETURN:
	            //未达到刷新界限，返回
	            mHeadText.setText("下拉刷新");
	            mHeadView.setPadding(mHeadView.getPaddingLeft(),
	                    0,
	                    mHeadView.getPaddingRight(),
	                    mHeadView.getPaddingBottom());
	            mPullRefreshState = PULL_REFRESH_NONE;
	            setSelection(1);
	            break;
	        case REFRESH_DONE:
	            //刷新结束后，恢复原始默认状态
	            mHeadText.setText("下拉刷新");
	            mHeadView.setPadding(mHeadView.getPaddingLeft(),
	                    0,
	                    mHeadView.getPaddingRight(),
	                    mHeadView.getPaddingBottom());
	            mPullRefreshState = PULL_REFRESH_NONE;
	            setSelection(1);
	            if (mRefreshListener != null) {
	            	mRefreshListener.refreshed(mRefreshObject);
	            }
	            break;
	        default:
	            break;
	        }
	    }
	};
	
	public interface RefreshListener {
	    Object refreshing();                //加载数据
	    void refreshed(Object obj);    //外部可扩展加载完成后的操作
	    void more(); //加载更多
	}
	
	@Override
	public void setAdapter(ListAdapter adapter) {
		// TODO Auto-generated method stub
		super.setAdapter(adapter);
		setSelection(1);
	}
	
}
